/* Copyright (c) 2011 by Mani Brundha Kattamuri, Haritha Subramanyam
 *
 * Project Info:  http://code.google.com/p/andriod-travelapp-csc780/wiki/Design
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 */
package com.example.TravelApp.search.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.util.Base64InputStream;
import android.util.Base64OutputStream;

/**
 * This class makes contains static methods that help in converting an object
 * into string (so that it can be saved using the shared preferences ) and
 * converting a string back into an object
 */
public class SerializablePlaceObject {

	/**
	 * Takes a Serializable object writes it to a output stream and converts
	 * into a byte array This byte array is finally converted to string
	 * 
	 * @param object
	 *            - Serializable object
	 * @return - String
	 */
	public static String objectToString(Serializable object) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			new ObjectOutputStream(out).writeObject(object);
			byte[] data = out.toByteArray();
			out.close();

			out = new ByteArrayOutputStream();
			Base64OutputStream b64 = new Base64OutputStream(out, 0);
			b64.write(data);
			b64.close();
			out.close();

			return new String(out.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Takes a string and converts it into a Serializable object
	 * 
	 * @param object
	 *            - String object
	 * @return - Object
	 */
	public static Object stringToObject(String encodedObject) {
		try {
			return new ObjectInputStream(new Base64InputStream(
					new ByteArrayInputStream(encodedObject.getBytes()), 0))
					.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
